<template>
  <uni-popup ref="popup" type="bottom" @change="onPopupChange">
    <view class="distribute-selector-modal">
      <view class="modal-header">
        <text class="modal-title">选择分发对象</text>
        <text class="close-btn" @click="close">✕</text>
      </view>

      <view class="modal-body">
        <scroll-view scroll-y class="content-scroll">
          <!-- 外部单位选择 -->
          <view class="section">
            <view class="section-header">
              <view class="checkbox-row" @click="toggleExternal">
                <text class="checkbox-icon">{{ enableExternal ? '☑' : '☐' }}</text>
                <text class="section-title">分发到外部单位</text>
              </view>
            </view>

            <view v-if="enableExternal" class="selection-area">
              <view v-if="companyLoading" class="loading-state">
                <text class="loading-text">加载中...</text>
              </view>
              <view v-else-if="companyList.length === 0" class="empty-state">
                <text class="empty-text">暂无可选单位</text>
              </view>
              <view v-else class="item-grid">
                <view
                  class="item-card"
                  v-for="company in companyList"
                  :key="company.id"
                  :class="{ 'is-selected': isCompanySelected(company.id) }"
                  @click="toggleCompany(company.id)"
                >
                  <view class="item-content">
                    <text class="item-name">{{ company.companyName }}</text>
                    <text class="item-desc" v-if="company.companyTypeDesc">{{
                      company.companyTypeDesc
                    }}</text>
                  </view>
                  <view class="selected-icon" v-if="isCompanySelected(company.id)">
                    <text>✓</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 内部部门选择 -->
          <view class="section">
            <view class="section-header">
              <view class="checkbox-row" @click="toggleInternal">
                <text class="checkbox-icon">{{ enableInternal ? '☑' : '☐' }}</text>
                <text class="section-title">分发到内部部门</text>
              </view>
            </view>

            <view v-if="enableInternal" class="selection-area">
              <view v-if="deptLoading" class="loading-state">
                <text class="loading-text">加载中...</text>
              </view>
              <view v-else-if="deptList.length === 0" class="empty-state">
                <text class="empty-text">暂无可选部门</text>
                <text class="empty-hint">请先设置部门负责人</text>
              </view>
              <view v-else class="item-grid">
                <view
                  class="item-card"
                  v-for="dept in deptList"
                  :key="dept.id"
                  :class="{ 'is-selected': isDeptSelected(dept.id) }"
                  @click="toggleDept(dept.id)"
                >
                  <view class="item-content">
                    <text class="item-name">{{ dept.deptName }}</text>
                    <text class="item-desc" v-if="dept.leaderName"
                      >负责人: {{ dept.leaderName }}</text
                    >
                  </view>
                  <view class="selected-icon" v-if="isDeptSelected(dept.id)">
                    <text>✓</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 已选择统计 -->
          <view class="summary" v-if="enableExternal || enableInternal">
            <text class="summary-title">已选择：</text>
            <view class="summary-tags">
              <view class="summary-tag external" v-if="enableExternal">
                <text>外部单位 {{ selectedCompanies.length }} 个</text>
              </view>
              <view class="summary-tag internal" v-if="enableInternal">
                <text>内部部门 {{ selectedDepartments.length }} 个</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <view class="modal-footer">
        <button class="cancel-btn" @click="close">取消</button>
        <button class="confirm-btn" :disabled="!canConfirm" @click="confirmSelection">
          确认分发
        </button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { getCompanyPage, type CompanyVO } from '@/Api/company'
import { getDeptList, type DeptInfo } from '@/Api/dept'
import { UserManager } from '@/utils/user'

interface Props {
  visible: boolean
  documentTitle?: string
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'confirm', data: DistributeData): void
}

export interface DistributeData {
  enableExternal: boolean
  enableInternal: boolean
  selectedCompanies: number[]
  selectedDepartments: Array<{
    deptId: number
    deptName: string
    leaderId: number
    leaderName: string
  }>
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const popup = ref<UniPopupInstance | null>(null)

// 外部单位相关
const enableExternal = ref(false)
const companyLoading = ref(false)
const companyList = ref<CompanyVO[]>([])
const selectedCompanies = ref<number[]>([])

// 内部部门相关
const enableInternal = ref(false)
const deptLoading = ref(false)
const deptList = ref<DeptInfo[]>([])
const selectedDepartments = ref<number[]>([])

// 是否可以确认
const canConfirm = computed(() => {
  if (!enableExternal.value && !enableInternal.value) {
    return false
  }
  if (enableExternal.value && selectedCompanies.value.length === 0) {
    return false
  }
  if (enableInternal.value && selectedDepartments.value.length === 0) {
    return false
  }
  return true
})

// 监听 visible prop 变化
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      popup.value?.open()
      resetSelection()
      loadCompanyList()
      loadDeptList()
    } else {
      popup.value?.close()
    }
  },
)

// 加载单位列表
const loadCompanyList = async () => {
  companyLoading.value = true
  try {
    const response = await getCompanyPage({
      pageNum: 1,
      pageSize: 1000,
      status: 1,
    })

    if (response.code === 200 && response.data) {
      let companies = response.data.records || []
      // 过滤掉当前用户的单位
      const userInfo = UserManager.getFullUserInfo()
      const currentCompanyId = userInfo.companyId
      if (currentCompanyId) {
        companies = companies.filter(
          (company: CompanyVO) => company.id !== Number(currentCompanyId),
        )
      }
      companyList.value = companies
      console.log('[DistributeSelector] 加载单位列表:', companies.length, '个')
    } else {
      uni.showToast({ title: response.message || '获取单位列表失败', icon: 'none' })
      companyList.value = []
    }
  } catch (error: any) {
    console.error('[DistributeSelector] 获取单位列表失败:', error)
    uni.showToast({ title: error.message || '获取单位列表失败', icon: 'none' })
    companyList.value = []
  } finally {
    companyLoading.value = false
  }
}

// 加载部门列表
const loadDeptList = async () => {
  deptLoading.value = true
  try {
    const userInfo = UserManager.getFullUserInfo()
    const companyId = userInfo.companyId
    if (!companyId) {
      uni.showToast({ title: '无法获取当前用户单位信息', icon: 'none' })
      deptList.value = []
      return
    }

    const response = await getDeptList({
      status: 1,
      companyId: Number(companyId),
    })

    if (response.code === 200 && response.data) {
      // 只显示有负责人的部门
      const deptsWithLeader = response.data.filter(
        (dept: DeptInfo) => dept.leaderId && dept.leaderName,
      )
      deptList.value = deptsWithLeader
      console.log('[DistributeSelector] 加载部门列表:', deptsWithLeader.length, '个')

      if (deptsWithLeader.length === 0) {
        uni.showToast({ title: '当前单位没有设置负责人的部门', icon: 'none' })
      }
    } else {
      uni.showToast({ title: response.message || '获取部门列表失败', icon: 'none' })
      deptList.value = []
    }
  } catch (error: any) {
    console.error('[DistributeSelector] 获取部门列表失败:', error)
    uni.showToast({ title: error.message || '获取部门列表失败', icon: 'none' })
    deptList.value = []
  } finally {
    deptLoading.value = false
  }
}

// 切换外部单位启用状态
const toggleExternal = () => {
  enableExternal.value = !enableExternal.value
  if (!enableExternal.value) {
    selectedCompanies.value = []
  }
}

// 切换内部部门启用状态
const toggleInternal = () => {
  enableInternal.value = !enableInternal.value
  if (!enableInternal.value) {
    selectedDepartments.value = []
  }
}

// 判断单位是否被选中
const isCompanySelected = (id: number) => {
  return selectedCompanies.value.includes(id)
}

// 切换单位选择状态
const toggleCompany = (id: number) => {
  const index = selectedCompanies.value.indexOf(id)
  if (index > -1) {
    selectedCompanies.value.splice(index, 1)
  } else {
    selectedCompanies.value.push(id)
  }
}

// 判断部门是否被选中
const isDeptSelected = (id: number) => {
  return selectedDepartments.value.includes(id)
}

// 切换部门选择状态
const toggleDept = (id: number) => {
  const index = selectedDepartments.value.indexOf(id)
  if (index > -1) {
    selectedDepartments.value.splice(index, 1)
  } else {
    selectedDepartments.value.push(id)
  }
}

// 重置选择
const resetSelection = () => {
  enableExternal.value = false
  enableInternal.value = false
  selectedCompanies.value = []
  selectedDepartments.value = []
}

// 确认选择
const confirmSelection = () => {
  if (!canConfirm.value) {
    uni.showToast({ title: '请至少选择一个分发对象', icon: 'none' })
    return
  }

  // 验证外部单位
  if (enableExternal.value && selectedCompanies.value.length === 0) {
    uni.showToast({ title: '已启用外部单位分发，请选择至少一个单位', icon: 'none' })
    return
  }

  // 验证内部部门
  if (enableInternal.value && selectedDepartments.value.length === 0) {
    uni.showToast({ title: '已启用内部部门分发，请选择至少一个部门', icon: 'none' })
    return
  }

  // 获取选中的部门详细信息
  const selectedDeptDetails = deptList.value
    .filter((dept) => selectedDepartments.value.includes(dept.id))
    .map((dept) => ({
      deptId: dept.id,
      deptName: dept.deptName,
      leaderId: dept.leaderId!,
      leaderName: dept.leaderName!,
    }))

  console.log('[DistributeSelector] 确认分发:', {
    enableExternal: enableExternal.value,
    enableInternal: enableInternal.value,
    selectedCompanies: selectedCompanies.value,
    selectedDepartments: selectedDeptDetails,
  })

  emit('confirm', {
    enableExternal: enableExternal.value,
    enableInternal: enableInternal.value,
    selectedCompanies: selectedCompanies.value,
    selectedDepartments: selectedDeptDetails,
  })

  close()
}

// 关闭弹窗
const close = () => {
  emit('update:visible', false)
  resetSelection()
}

// Popup 状态变化
const onPopupChange = (e: { show: boolean }) => {
  if (!e.show) {
    emit('update:visible', false)
  }
}
</script>

<style lang="scss" scoped>
.distribute-selector-modal {
  background: white;
  border-radius: 32rpx 32rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .modal-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .close-btn {
    font-size: 48rpx;
    color: #999;
    line-height: 1;
  }
}

.modal-body {
  flex: 1;
  overflow: hidden;

  .content-scroll {
    height: 100%;
    max-height: 60vh;
  }
}

.section {
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }
}

.section-header {
  margin-bottom: 24rpx;

  .checkbox-row {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .checkbox-icon {
      font-size: 40rpx;
      color: #409eff;
    }

    .section-title {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
    }
  }
}

.selection-area {
  margin-top: 16rpx;
}

.loading-state,
.empty-state {
  text-align: center;
  padding: 60rpx 0;

  .loading-text,
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }

  .empty-hint {
    display: block;
    font-size: 24rpx;
    color: #ccc;
    margin-top: 8rpx;
  }
}

.item-grid {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.item-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;

  &.is-selected {
    background: #e3f2fd;
    border-color: #409eff;
  }

  .item-content {
    flex: 1;

    .item-name {
      display: block;
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 8rpx;
    }

    .item-desc {
      display: block;
      font-size: 24rpx;
      color: #999;
    }
  }

  .selected-icon {
    width: 48rpx;
    height: 48rpx;
    background: #409eff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;

    text {
      font-size: 32rpx;
      color: white;
      font-weight: bold;
    }
  }
}

.summary {
  padding: 24rpx 32rpx;
  background: #f5f7fa;

  .summary-title {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 16rpx;
    display: block;
  }

  .summary-tags {
    display: flex;
    gap: 16rpx;
    flex-wrap: wrap;
  }

  .summary-tag {
    padding: 12rpx 24rpx;
    border-radius: 8rpx;
    font-size: 24rpx;

    &.external {
      background: #e3f2fd;
      color: #409eff;
    }

    &.internal {
      background: #f0fdf4;
      color: #67c23a;
    }
  }
}

.modal-footer {
  display: flex;
  gap: 24rpx;
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f0f0f0;
  background: white;

  button {
    flex: 1;
    height: 88rpx;
    border-radius: 16rpx;
    font-size: 30rpx;
    border: none;
  }

  .cancel-btn {
    background: #f5f5f5;
    color: #666;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .confirm-btn {
    background: #409eff;
    color: white;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;

    &:disabled {
      background: #e0e0e0;
      color: #bbb;
    }
  }
}
</style>
